<template>
    <v-container v-if="!showErrorPage">
        <AdminCommonCURD :config="curdComponentConfig" :addClickListener="addClickListener"
            :filter-listener="filterListener" :importClickListener="importListener" 
            :backwardClickListener="curdComponentConfig.backwardBtn.click" />
        <v-data-table-server v-show="!curdComponentConfig.backwardBtn.visible" :hover="true" :fixed-header="true" 
            :loading="listLoading" :headers="headers"
            :items="bookList" :height="tableHeight" item-value="bookId" show-select
            v-model:items-per-page="bookBo.pageSize" :items-length="total" @update:options="loadItems"
            items-per-page-text="每页数据量" :items-per-page-options="[10, 20, 30, 40, 50, 100]">
            <template v-slot:item.actions="{ item }">
                <v-icon class="me-2" icon="mdi-eye-outline" @click="viewWordDetail(item.data)"></v-icon>
                <v-icon v-hasPermi="['update-book-admin']" class="me-2" icon="mdi-pencil-outline"
                    @click="updateWordDialog(item.data)"></v-icon>
                <v-icon class="me-2" icon="mdi-format-align-left" @click="listWordListOfBook(item.bookId)"></v-icon>
                <v-icon v-hasPermi="['update-book-admin']" class="me-2" icon="mdi-delete-outline"
                    @click="deleteWordDelete(item.data)"></v-icon>
            </template>
        </v-data-table-server>
        <admin-word-list-in-book ref="adminWordListInBook" v-show="curdComponentConfig.backwardBtn.visible"/>
    </v-container>
    <Error401 v-else />
    <v-dialog v-model="commonDialogConfig.visible" persistent :width="commonDialogConfig.width">
        <v-card :prepend-icon="commonDialogConfig.prependIcon" :title="commonDialogConfig.title">
            <v-card-text>
                <AdminEditBookComponent v-if="commonDialogConfig.name == 'save' || commonDialogConfig.name == 'update'"
                    :labelList="labelList" :langList="langList" ref="AdminEditBookComponent" />
                <p v-else-if="commonDialogConfig.name == 'delete'">确认删除
                    <strong style="color:#2196F3">{{ commonDialogConfig.content }}</strong>
                    ？
                </p>
            </v-card-text>
            <template v-slot:actions>
                <v-spacer></v-spacer>
                <v-btn @click="resetCommonDialog">
                    取消
                </v-btn>
                <v-btn v-if="commonDialogConfig.name == 'save' || commonDialogConfig.name == 'update'" color="primary"
                    @click="saveBook">
                    确定
                </v-btn>
                <v-btn v-if="commonDialogConfig.name == 'delete'" color="warning"
                    @click="confirmDelete(commonDialogConfig.data)">
                    确认删除
                </v-btn>
            </template>
        </v-card>
    </v-dialog>
    <v-snackbar v-model="snackbar">
        {{ snackbarMsg }}
    </v-snackbar>
    <v-overlay :model-value="overlay" class="align-center justify-center">
        <v-progress-circular color="primary" indeterminate size="64"></v-progress-circular>
    </v-overlay>
</template>

<script>
import { langList } from "@/api/lang.js";
import { adminLabelList } from "@/api/label.js";
import { adminBookList } from "@/api/book.js";
import { formatTimestamp } from "@/util/ruoyi";
import AdminEditBookComponent from '@/components/AdminEditBookComponent.vue';
import { adminDeleteBook, adminGetBookWordLineCount } from "@/api/adminBook";
import Error401 from '../error/Error401.vue';
import AdminCommonCURD from "@/components/AdminCommonCURD.vue";
import AdminWordListInBook from '@/components/AdminWordListInBook.vue';
export default {
    components: { AdminEditBookComponent, Error401, AdminCommonCURD, AdminWordListInBook },
    data() {
        return {
            showErrorPage: false,
            curdComponentReadonly: false,
            headers: [
                { title: "ID", align: "start", key: "bookId" },
                { title: "标题", align: "start", key: "title", minWidth: 150 },
                { title: "描述", align: "start", key: "remark", },
                { title: "数量", align: "start", key: "count", width: 90 },
                { title: "语种", align: "start", key: "language", width: 90 },
                { title: "标签", align: "start", key: "label", minWidth: 90 },
                { title: "创建日期", align: "start", key: "createAt", width: 120 },
                { title: "操作", align: "start", key: "actions", width: 150 },
            ],
            bookBo: {
                pageSize: 20,
                pageNum: 1,
            },
            total: 0,
            listLoading: false,
            langList: [],
            labelList: [],
            bookList: [],
            langMap: {},
            showingBokkId:null,
            commonDialogConfig: {},
            snackbar: false,
            snackbarMsg: undefined,
            overlay: false,
            curdComponentConfig: {
                backwardBtn:{},
                addBtn: {},
                batchImportBtn: {},
                batchDeleteBtn: {},
                searchBtn: {},
            },
        };
    },
    created() {
        this.tableHeight = window.innerHeight - 64 - 56 - 58;
        this.getSelectData();
        this.curdComponentInit()
    },
    methods: {
        getSelectData() {
            langList({}).then((resp) => {
                this.langList = resp.data;
                this.langList.forEach((item) => {
                    this.langMap[item.langId] = item;
                });
            });
            adminLabelList({}).then((resp) => {
                this.labelList = resp.data;
            });
        },
        loadItems({ page, itemsPerPage }) {
            this.listLoading = true;
            this.bookBo.pageNum = page;
            this.bookBo.pageSize = itemsPerPage;
            adminBookList()
                .then((resp) => {
                    if (resp.code === 403 || resp.code === 401) {
                        this.showErrorPage = true
                        return
                    }
                    if (resp.code == 1) {
                        this.getPresetBookList(resp.rows);
                        this.total = resp.total;
                    }
                })
                .finally(() => (this.listLoading = false));
        },
        getPresetBookList(bookList) {
            this.bookList = [];
            if (bookList == null) return;
            bookList.forEach((bookItem) => {
                var singleBookItem = this.singleBookHandler(bookItem)
                this.bookList.push(singleBookItem);
            });
            for (let i = 0; i < this.bookList.length; i++) {
                adminGetBookWordLineCount(this.bookList[i].bookId).then(resp => { this.bookList[i].count = resp.data })
            }
        },
        singleBookHandler(bookItem) {
            let singleBook = {};
            singleBook.data = bookItem;
            singleBook.bookId = bookItem.id;
            singleBook.title = bookItem.title;
            singleBook.remark = bookItem.remark;
            if (bookItem.langId != null && this.langMap[bookItem.langId] != null) singleBook.language = this.langMap[bookItem.langId].root;
            singleBook.createAt = formatTimestamp(bookItem.createAt);
            singleBook.count = 'loading'
            return singleBook;
        },
        saveBook() {
            this.overlay = true
            setTimeout(() => {
                this.overlay = false
            }, 1000);
            this.$refs.AdminEditBookComponent.save(this.commonDialogConfig.name, (result) => {
                this.overlay = false
                if (result) {
                    this.resetCommonDialog()
                    this.loadItems({ page: 1, itemsPerPage: this.bookBo.pageSize })
                }
            })
        },
        updateWordDialog(word) {
            this.commonDialogConfig.title = "修改词典"
            this.commonDialogConfig.name = 'update'
            this.commonDialogConfig.visible = true
            this.commonDialogConfig.prependIcon = 'mdi-update'
            setTimeout(() => {
                this.$refs.AdminEditBookComponent.setBookBo(word)
            }, 300);
        },
        deleteWordDelete(book) {
            this.commonDialogConfig.title = "删除词典"
            this.commonDialogConfig.name = 'delete'
            this.commonDialogConfig.visible = true
            this.commonDialogConfig.prependIcon = 'mdi-delete'
            this.commonDialogConfig.content = book.title
            this.commonDialogConfig.data = [book.id]
            // this.commonDialogConfig.width=300
        },
        confirmDelete(bookIdList) {
            this.overlay = true
            adminDeleteBook(bookIdList).then(resp => {
                this.overlay = false
                if (resp.code == 1) {
                    this.resetCommonDialog()
                    this.loadItems({ page: 1, itemsPerPage: this.bookBo.pageSize })
                }
            })
        },
        addClickListener() {
            this.commonDialogConfig.title = "添加词典";
            this.commonDialogConfig.name = "save";
            this.commonDialogConfig.visible = true;
            this.commonDialogConfig.prependIcon = "mdi-plus-box";
        },
        listWordListOfBook(bookId){
            this.curdComponentConfig.backwardBtn.visible=true
            this.showingBokkId=bookId
            this.$refs.adminWordListInBook.manualRefresh(bookId)
        },
        filterListener() { },
        importListener() { },
        resetCommonDialog() {
            this.commonDialogConfig = {}
        },
        curdComponentInit(){       
            if (!this.$store.state.userPermissionArray.includes('read-book-admin')) 
                this.showErrorPage = true
            else if (this.$store.state.userPermissionArray.includes('update-book-admin')) {
                this.curdComponentConfig.backwardBtn.visible = false
                this.curdComponentConfig.addBtn.visible = true
                this.curdComponentConfig.searchBtn.visible = true
                this.curdComponentConfig.batchImportBtn.visible = true
                this.curdComponentConfig.batchDeleteBtn.visible = true
            }else this.curdComponentConfig.searchBtn.visible = true
            this.curdComponentConfig.backwardBtn.click=()=>{
                this.curdComponentConfig.backwardBtn.visible=false
            }
        }
    },
    watch: {
        '$store.state.userPermissionArray'() {
            // this.curdComponentInit()
        }
    }
};
</script>

<style scoped>
@media (min-width: 1280px) {
    .v-container {
        max-width: 100%;
        padding: 10px;
    }
}
</style>